import { Component, OnInit, Output, OnDestroy, Input, EventEmitter } from '@angular/core';
import 'rxjs/add/operator/switchMap';
import { appService } from '../../../../../my-service/app.service';
import { UtilService } from '../../../../../my-service/util.service'
import { DomSanitizer } from '@angular/platform-browser';
declare var $: any;
declare var io: any;
@Component({
  selector: 'notecanvas-root',
  templateUrl: './notecanvas.component.html',
  styleUrls: ['./notecanvas.component.css']
})
export class notecanvasComponent implements OnInit, OnDestroy {
  pointerArray = [];//锚点数据
  updata = false;
  socket;
  dropLine=0;//断线次数
  addwindow = false;
  canopenadd = false;//控制详情弹出框的
  canhover = false;//控制hover详情的
  private pointdata: any;//单个的锚点数据，准备传给详情弹出框
  private notedata: any;//标签数据，准备传给详情弹出框
  config = {
    HaveTitle: 0,
    HaveAuthor: 0,
    PK_AnchorGuid: ''
  }
  @Input() CanvasGroupGuid: any;
  @Input() mainH: any;
  @Input() mainW: any;
  @Output() deldata = new EventEmitter<Event>();
  constructor(
    private appservice: appService, private _sanitizer: DomSanitizer,private UtilService: UtilService
  ) { }
  ngOnInit() {
    this.getpoint();
    //监听socket
    this.socket = io('ws://47.106.117.200:6101/');
    // this.socket = io('ws://localhost:6101/');
    // this.socket = io('ws://211.149.221.44:6101/');
    // this.socket = io('ws://132.232.143.47:6101/');
    this.socket.on('connect', () => {
      this.socket.emit('Host', { FK_CanvasGroupGuid: this.CanvasGroupGuid })
    })
    this.socket.on('disconnect', () => {
        this.dropLine++
        console.log(new Date())
        if(this.dropLine==1){
            console.log(new Date())
            location.reload();
        }
    })
    this.socket.on('re', (re) => {
      this.appservice.getonenote(re.PK_NoteGuid).then((res) => {
        this.pointerArray.forEach(element => {//遍历锚点
          if (element.PK_AnchorGuid == res.FK_AnchorGuid) {//如果锚点guid与note的guid相同
            element.note.push({//向最小值标签中创建新的post的标签,以此改变全局变量pointerArray的数据，以达到更新视图的作用。
              PK_NoteGuid: res.PK_NoteGuid,
              Name: res.Name,
              FK_CanvasGroupGuid: this.CanvasGroupGuid,
              Content: res.Content,
              Color: res.Color,
              FK_AnchorGuid: res.FK_AnchorGuid,
              Title: res.Title
            })
            let min = element.Coordinate[0].note;//设置最小值数组用来存新添加的标签
            for (let i = 0; i < element.Coordinate.length; i++) {//遍历锚点中的坐标
              if (element.Coordinate[i].note.length < min.length) {//如果锚点中的坐标中的标签的数量小于最小值标签
                min = element.Coordinate[i].note;//则更新最小值标签
              }
            }
            min.push({//向最小值标签中创建新的post的标签,以此改变全局变量pointerArray的数据，以达到更新视图的作用。
              PK_NoteGuid: res.PK_NoteGuid,
              Name: res.Name,
              Content: res.Content,
              Color: res.Color,
              FK_AnchorGuid: res.FK_AnchorGuid,
              Title: res.Title
            })
          }
        });
      })
    })
  }
  //获取锚点
  getpoint() {
    this.appservice.getPointer(this.CanvasGroupGuid).then(re => {//ge所有的锚点
      for (let i = 0; i < re.length; i++) {//遍历锚点
        re[i].Coordinate = JSON.parse(re[i].Coordinate);//将锚点中的坐标值转为数组
        re[i].AddCoordinate = JSON.parse(re[i].AddCoordinate);
        re[i].note = [];
        for (let j = 0; j < re[i].Coordinate.length; j++) {//遍历坐标值数组
          re[i].Coordinate[j].note = []; //初始化坐标值数组
        }
        if(re[i].Color)   re[i].ChangeColor = `-webkit-linear-gradient(${this.appservice.RGB2RGBA(re[i].Color, .6)},${re[i].Color},${re[i].Color})`
      }
      this.appservice.getallnote(this.CanvasGroupGuid).then((res) => {
        for (let i = 0; i < res.length; i++) {
          re.forEach(element => {
            if (element.PK_AnchorGuid == res[i].FK_AnchorGuid) {
              element.note.push(res[i])
              let min = element.Coordinate[0].note;
              for (let i = 0; i < element.Coordinate.length; i++) {
                if (element.Coordinate[i].note.length < min.length) {
                  min = element.Coordinate[i].note;
                }
              }
              min.push(res[i]);
            }
          });
        }
        this.pointerArray = re;
      })
    }).then(() => {
      this.canopenadd = false;
      this.updata = false;
    })
  }
  hover(k, j, length) {
    if (length > 1) {
      $(`#point${k}hover${j}`).show(50);
    }
  }
  hoverend(k, j, length) {
    if (length > 1) {
      $(`#point${k}hover${j}`).hide(50);
    }
  }
  //打开详情界面
  openadd(pointer, length) {
    if (length > 0) {
      this.pointdata = pointer;
      this.canopenadd = true;
    }
    else { return }
  }
  //关闭详情界面
  closeAdd() {
    if (this.updata) {
      this.getpoint()
    }
    else {
      this.canopenadd = false
    }
  }
  //添加
  add($event) {
    this.updata = true;
    this.addwindow = true;
    this.config = {
      HaveAuthor: $event.HaveAuthor,
      HaveTitle: $event.HaveTitle,
      PK_AnchorGuid: $event.PK_AnchorGuid
    }
    this.addnote($event.PK_AnchorGuid, $event.color, $event.HaveTitle, $event.HaveAuthor)
  }
  addnote(PK_AnchorGuid, color, HaveTitle, HaveAuthor) {
    this.addwindow = true;
    this.config = {
      HaveAuthor: HaveAuthor,
      HaveTitle: HaveTitle,
      PK_AnchorGuid: PK_AnchorGuid
    }
  }
  //标签添加框的事件
  oncancel() {
    this.addwindow = false;
    this.config = {
      HaveTitle: 0,
      HaveAuthor: 0,
      PK_AnchorGuid: ''
    }
  }
  onok(data) {
    this.addwindow = false;
    this.config = {
      HaveTitle: 0,
      HaveAuthor: 0,
      PK_AnchorGuid: ''
    }
    data.PK_NoteGuid = this.appservice.GenGuid();//生成新标签的guid
    data.FK_CanvasGroupGuid = this.CanvasGroupGuid;
    this.appservice.postnote(data).then(re => {//向数据库中标签表post数据
      if (re.status == "success") {
        this.pointerArray.forEach(element => {//遍历锚点
          if (element.PK_AnchorGuid == data.PK_AnchorGuid) {//如果锚点guid与note的guid相同
            element.note.push({//向最小值标签中创建新的post的标签,以此改变全局变量pointerArray的数据，以达到更新视图的作用。
              PK_NoteGuid: data.PK_NoteGuid,
              Name: data.name,
              FK_CanvasGroupGuid: data.FK_CanvasGroupGuid,
              Content: data.Content,
              Color: data.color,
              FK_AnchorGuid: data.PK_AnchorGuid,
              Title: data.Title
            })
            let min = element.Coordinate[0].note;//设置最小值数组用来存新添加的标签
            for (let i = 0; i < element.Coordinate.length; i++) {//遍历锚点中的坐标
              if (element.Coordinate[i].note.length < min.length) {//如果锚点中的坐标中的标签的数量小于最小值标签
                min = element.Coordinate[i].note;//则更新最小值标签
              }
            }
            min.push({//向最小值标签中创建新的post的标签,以此改变全局变量pointerArray的数据，以达到更新视图的作用。
              PK_NoteGuid: data.PK_NoteGuid,
              Name: data.name,
              Content: data.Content,
              Color: data.color,
              FK_AnchorGuid: data.PK_AnchorGuid,
              Title: data.Title
            })
          }
        });
      }
    })
  }
  //16进制颜色转rgba
  RGB2RGBA(rgb_color, alp) {
    let r = parseInt(`0x${rgb_color.substr(1, 2)}`);
    let g = parseInt(`0x${rgb_color.substr(3, 2)}`);
    let b = parseInt(`0x${rgb_color.substr(5, 2)}`);
    let a = alp;
    return `rgba(${r},${g},${b},${a})`;
  }
  //通过angular的外来注入检查
  Color(color) {
    return this._sanitizer.bypassSecurityTrustStyle(color);
  }
  //删除
  del($event) {
    this.updata = true;
    this.appservice.delnote($event).then(re => {
      if (re.PK_NoteGuid) {
        for (let i = 0; i < this.pointerArray.length; i++) {
          for (let j = 0; j < this.pointerArray[i].Coordinate.length; j++) {
            for (let k = 0; k < this.pointerArray[i].Coordinate[j].note.length; k++) {
              if (re.PK_NoteGuid == this.pointerArray[i].Coordinate[j].note[k].PK_NoteGuid) {
                this.pointerArray[i].Coordinate[j].note.splice(k, 1);
              }
            }
          }
        }
      }
      return re
    }).then((re) => {
      for (let i = 0; i < this.pointerArray.length; i++) {
        for (let m = 0; m < this.pointerArray[i].note.length; m++) {
          if (re.PK_NoteGuid == this.pointerArray[i].note[m].PK_NoteGuid) {
            this.pointerArray[i].note.splice(m, 1);
          }
        }
      }
    }).then(() => {
      this.appservice.getDelNote(this.CanvasGroupGuid).then(re => {
        re.forEach(element => {
          element.ChangeColor = `-webkit-linear-gradient(${this.RGB2RGBA(element.Color, .6)},${element.Color},${element.Color})`
        });
        this.deldata.emit(re);
      })
    })
  }
  Recovery(PK_NoteGuid) {
    this.appservice.getonenote(PK_NoteGuid).then((re) => {
      this.pointerArray.forEach(element => {
        if (element.PK_AnchorGuid == re.FK_AnchorGuid) {
          element.note.push({
            Content: re.Content,
            FK_AnchorGuid: re.FK_AnchorGuid,
            FK_CanvasGroupGuid: this.CanvasGroupGuid,
            Name: re.Name,
            PK_NoteGuid: re.PK_NoteGuid,
            Title: re.Title
          })
          let min = element.Coordinate[0].note;
          for (let i = 0; i < element.Coordinate.length; i++) {
            if (element.Coordinate[i].note.length < min.length) {
              min = element.Coordinate[i].note;
            }
          }
          min.push({
            Content: re.Content,
            FK_AnchorGuid: re.FK_AnchorGuid,
            FK_CanvasGroupGuid: this.CanvasGroupGuid,
            Name: re.Name,
            PK_NoteGuid: re.PK_NoteGuid,
            Title: re.Title
          });
        }
      });
    })
  }
  charts(CanvasType, Name, chartsType) {
    let notelength = 5
    let chartsData = { "name": Name, "children": [] }
    for (let i = 0; i < this.pointerArray.length; i++) {
      chartsData.children.push({
        'name': this.pointerArray[i].AnchorName,
        'children': []
      })
      if (this.pointerArray[i].note.length < 5) notelength = this.pointerArray[i].note.length
      for (let j = 0; j < notelength; j++) {
        let _content2 = this.pointerArray[i].note[j].Content
        _content2 = _content2.replace(/[\r\n]/g, " ")
        if (chartsType == 'charts' && _content2.length > 46) {
          _content2 = _content2.substring(0, 46) + '......'

        }
        chartsData.children[i].children.push({
          'name': _content2
        })
      }
    }
    return chartsData
  }
  //组件销毁的时候，把socket注销了
  ngOnDestroy() {
    this.socket.close();
  }
}
